/*
 * Copyright (c) 2020-2022 Jinsp-tech. All rights reserved.
 */

package com.jinsp.networklibrary;

import android.util.Log;

import com.jinsp.networklibrary.command.CommandManager;
import com.jinsp.networklibrary.command.TCPBaseDataBeanFactory;
import com.jinsp.networklibrary.command.TCPCommandData;
import com.jinsp.networklibrary.command.TCPCommandFactory;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * Created by luoshuai on 1/13/22
 * <p>
 * 处理服务端返回的消息
 */
class TCPMessageHandler extends IoHandlerAdapter {

    private final String TAG = "TCPMessageHandler";

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        Log.d(TAG, "检测到空闲状态：" + status.toString());
        if (status == IdleStatus.READER_IDLE) {
            TCPSessionManager.getInstance().setTcpReadIdle(true);
        }
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        TCPSessionManager.getInstance().setTcpReadIdle(false);
        Log.d(TAG, "收到服务消息：" + message);
        //交给具体命令处理器处理
        if (message instanceof TCPCommandData) {
            TCPCommandData tcpCommandData = (TCPCommandData) message;
            CommandManager.getInstance().dispatchCommand(tcpCommandData);
        }
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        Log.d(TAG, "TCP通信发生异常：" + cause.getMessage());
        cause.printStackTrace();
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        Log.d(TAG, "TCP连接关闭");
        TCPSessionManager.getInstance().release();
        TCPCommandFactory.release();
        TCPBaseDataBeanFactory.release();
    }
}
